package mammuthus.controller.app

import net.csdn.annotation.rest.{State, BasicInfo, At}
import net.csdn.modules.http.{ApplicationController, ViewType, RestRequest}
import java.io.File
import net.liftweb.{json => SJSon}
import mammuthus.tool.Constants
import com.google.inject.Inject
import mammuthus.master.Master
import net.csdn.common.env.Environment
import mammuthus.controller.filter.{TokenAuthFilter, AppNameCheckFilter}

/**
 * 6/9/15 WilliamZhu(allwefantasy@gmail.com)
 */
class AppStoreTaskController @Inject()(akkaMaster: Master, env: Environment) extends ApplicationController with TokenAuthFilter with AppNameCheckFilter{

  implicit val formats = SJSon.Serialization.formats(SJSon.NoTypeHints)

  val appRootDir = Constants.getAppRootDir

  def appName = param("appName")
  @At(path = Array("/app/store"), types = Array(RestRequest.Method.GET, RestRequest.Method.POST))
  @BasicInfo(
    desc = "获取可供安装的应用",
    state = State.alpha,
    testParams = "/app/store",
    testResult = "",
    author = "WilliamZhu",
    email = "allwefantasy@gmail.com"
  )
  def appStore = {
    auth

    val res = new File(env.templateDirFile().getPath + "/assets/").list().map {
      file =>
        val name = file.replace(".tar.gz", "")
        val arr = name.split("@")
        if (arr.length == 2) (arr(0), arr(1)) //appName, appVersion
        else null
    }.filter(_ != null).groupBy(_._1).map(l => Map("appName" -> l._1, "version" -> l._2.map(_._2).reverse)).toList.reverse

    render(SJSon.Serialization.write(res), ViewType.json)
  }
}
